import {observable,action} from 'mobx';
import { WeaTableNew } from 'comsMobx';
import { message, Button } from 'antd';
import * as goalDetail from '../../apis/goal/goalDetail';
import * as goalAdd from '../../apis/goal/goalAdd'
import * as goalCommonAPI from '../../apis/goal/goalCommon'
import {WeaLocaleProvider} from 'ecCom';
import * as Util from "../../util/Util";
const toJS = mobx.toJS;
const getLabel = WeaLocaleProvider.getLabel;
const { TableStore } = WeaTableNew;
export default class GoalDetailStore{

    @observable loading = true; // 页面初始化的loading状态：数据加载成功前后前使用
    @observable hasRight = true; // 判断用户是有权限查看当前页面： 没有权限渲染无权限页面，有权限渲染数据
    @observable feedBackData = {
        count:'',
        lastcount:0,
        list:[]
    }
    @observable moreFeedBackData = []; //更多反馈内容
    @observable goalLog = {            //目标的日志
        lastid:'',
        lastcount:'',
        list:[],
    };
    @observable parentData = {}; //上级目标的id,name
    @observable isSpecial = false; //是否关注
    @observable topBtns = [];   // 顶部按钮
    @observable detailData = {
        id:'',          //主键
        name:'',        //目标名称            
        status:'',      //目标状态
        cate:'',        //目标类型 目前E8分类为五类 1-财务效益类 2-客户运营类 3-内部经营类 4-学习成长类 5-备忘类
        remark:'',      //描述
        target:'',      //目标值
        tunit:'',       //目标值单位
        result:'',      //完成值
        runit:'',       //完成值单位
        rate:'',        //完成率
        period:'',      //周期 1-月度 2-季度 3-年度 4-三年 4-五年
        principalid:'', //目标责任人id
        partnerid:'',  //目标参与人id
        sharerid:'',   //目标分享人id
        begindate:'',   //目标开始时间
        enddate:'',     //目标结束时间
        parentid:'',    //上级目标
        taskids:'',     //相关任务id
        docids:'',      //相关文档id
        wfids:'',       //相关流程id
        meetingids:'',  //相关会议id
        crmids:'',      //相关客户id
        projectids:'',  //相关项目id
        goalids:'',     //相关目标id
        planids:'',     //相关报告id
        fileids:'',     //相关附件id
        creater:'',     //目标创建者id
        createrlink:'',    //目标创建标签a
        createdate:'',  //目标创建日期
        createtime:'',  //目标创建时间
        updater:'',     //目标更改者id
        updatedate:'',  //目标更新日期
        updatetime:'',  //目标更新时间
        deleted:'',     //目标是否删除
        showallsub:'',  //是否开放所有下级目标的查看权限
        showorder:'',   //排序
        cancreate:false,
        canedit:false,
        caneditPrincial:false,
        canDelete:false,
        isTask:false,
        tag: '',//标签

        relateDocs:[],  //相关文档
        relateFileds:[],//相关附件
        relateGoals:[], //相关目标
        relateProjects:[],//相关项目
        relateTasks:[],   //相关任务
        relateWorkFlows:[],//相关流程
        relateCutomer:[], //相关客户
        principalid_arr:[], //负责人数组
        partnerid_arr:[],//参与人数组
        sharerid_arr:[],//分享人数组
        parentGoal:[],
        tagArray: [],//标签
    }
    @observable subGoalList = [];//下级目标
    @observable connectGoals = [];//被关联的目标
    @observable connectTasks = [];//被关联的任务
    @observable detailKey = "";

    @observable optparams = {};//ViewTree组件操作数组
    @observable localtime = new Date().getTime();
    @observable flag = true; //是否刷新上传组件
    scrollstatus = 0;//滚动条滚动状态
    @observable cubeLayoutParame = {};//装载布局请求入参
    @observable Card = {};
    // isloading = true;
    @observable cubeLoading = true //建模加载 
    @observable optionTypes = []; // 分类选项
    @observable category = ''; //文件上传目录
    @observable maxUploadSize = '' //最大的上传文件的大小
    @observable iconType = '1' //判断打开方式 1侧边打开 2直接打开
    @observable isFirstLog = 1; //是否第一次打开 1是 0否
    @observable dropdisplay = true; //是否展示
    @observable dropSelectedKey = 1; //1批量删除 2批量标记
    @observable checkedIds = '';
    @observable tagChoiceBoxVisible = false;
    @observable taskitemTaglistPopoverVisible = false;
    @observable subtagvisible = false;
    opentagtype = 1;
    selectgoalid = "";//选中的目标
    @observable allCheckBoxVal = "0";//子目标checkbox框的值
    @observable orgId = "1"; //组织结构id 默认总部id
    @observable type = "1"; //类型 1公司 2分部 3部门

    //共享
    @observable shareTableStore = new TableStore(); // 
    @observable shareConditioninfo = [];
    @observable disabled = true; //共享权限删除按钮
    @observable isOrgGoal = false; // 是否为组织目标
    //初始化信息
    @action
    initData = (feedBackParams,subParams) =>{
        this.getGoalFeedBack(feedBackParams)
        this.getSubGoalList(subParams);
    }

    //获取详细信息
    @action
    getDetailView = (params) => {
        this.loading = true;
        goalDetail.getDetailView(params).then(action(res=>{
            if(res.status){
                if(res.hasDelete){
                    this.detailKey = "";//目标被删除
                }else if(!res.hasRight){
                    this.hasRight = res.hasRight;
                }else{
                    this.hasRight = res.hasRight;
                    this.detailData = res.data;
                    this.isSpecial = res.isSpecial;
                    this.connectGoals = res.connectGoals;
                    this.connectTasks = res.connectTasks;
                    this.isOrgGoal = res.isOrgGoal;
                    this.setOptionsType(res.cateList); //设置分类
                    this.isFirstLog = 1; //重置第一次加载
                    this.dropdisplay = true;
                    this.dropSelectedKey = 1;
                    this.allCheckBoxVal = "0";
                    this.setButton(this.isSpecial,this.detailData.status,this.detailData.canedit,this.detailData.canDelete)
                    // if(typeof params.setBtn === "function"){
                    //     params.setBtn(this.isSpecial,this.detailData.status,this.detailData.canedit);
                    // }
                    if (typeof params.doback === "function") {
                        params.doback(this.detailData.viewdate);
                    }
                }

            }else if(!res.api_status){
                message.error(res.msg || getLabel('25009','失败'));
            }  
            this.loading = false;
        }));
    }

    //建模表单初始化
    @action
    initForm = params => {
        this.cubeLoading = true;
        goalAdd.getGoalSetupInit(params).then(action((result) => {
            if (result.status == 1 && result.isopen === true) {
                // this.hasData = true;
                this.cubeLayoutParame = { ...result.data };
            } else {
                this.cubeLayoutParame = {};
            }
            // this.isloading = false;
            if (typeof params.doback === "function") {
                params.doback();
            }
        }));
    }
    @action
    getCardStorefun = (store) => {
        this.Card = store;
        // this.cubeLoading = false;
    }

    @action
    getGoalFeedBack = (params) => {
        this.loading = true;
        goalDetail.getGoalFeedBack(params).then(action(res=>{
            if(res.status){
                this.feedBackData.count = res.count;
                this.feedBackData.lastcount = res.count - 5;
                this.feedBackData.list= res.list;
                this.loading = false;
            }else if(!res.api_status){
                this.loading = false;
                message.error(res.msg || getLabel('25009','失败'));
            }else{
                this.loading = false;
            }
        }));
    }

    @action
    addGoalFeedBack = (params) => {
        this.loading = true;
        goalDetail.addGoalFeedBack(params).then(action(res=>{
            if(res.status){
                let list = toJS(this.goalLog.list)
                list.unshift(res.logMap)
                this.goalLog.list = list;
                this.feedBackData.list.unshift(res.datas[0]);
                this.loading = false;
                if (typeof params.doback === "function") {
                    params.doback()
                }
            }else if(!res.api_status){
                this.loading = false;
                message.error(res.msg || getLabel('25009','失败'));
            }else{
                this.loading = false;
            }
        }))
    }

    @action
    delGoalFbInfo = (params) => {
        this.loading = true;
        goalDetail.delGoalFbInfo(params).then(action(res=>{
            if(res.status){
                let list = toJS(this.goalLog.list)
                list.unshift(res.logMap)
                this.goalLog.list = list;
                this.loading = false;
                this.feedBackData.list.splice(params.index,1) 
                message.success(getLabel(20461,'删除成功'))
            }else if(!res.api_status){
                this.loading = false;
                message.error(res.msg || getLabel('25009','失败'));
            }else{
                this.loading = false;
            }
        }))
    }

    //获取更多的反馈信息
    @action
    getMoreGoalFeedBack = (params) => {
        this.loading = true;
        goalDetail.getMoreGoalFeedBack(params).then(action(res=>{
            if(res.status){
                this.feedBackData.list= this.feedBackData.list.concat(res.list);
                this.feedBackData.lastcount = this.feedBackData.lastcount - 3;
                this.loading = false;
            }else if(!res.api_status){
                this.loading = false;
                message.error(res.msg || getLabel('25009','失败'));
            }else{
                this.loading = false;
            }
        }))
    }

    //获取的子目标
    @action
    getSubGoalList = (params) => {
        this.loading = true;
        goalDetail.getSubGoalList(params).then(action(res=>{
            if(res.status){
                if (params.type == 'father') {
                    this.subGoalList = res.subGoalList;
                } else {
                    this.localtime = new Date().getTime();
                    this.optparams = {};
                    this.optparams.datas = res.subGoalList;
                    this.optparams.opttype = "childs";
                    this.optparams.optkey = params.goalId;    
                    
                }
            }else if(!res.api_status){
                message.error(res.msg || getLabel('25009','失败'));
            }
            this.loading = false;
        }))
    }

    //编辑详细信息
    @action
    editGoalField = (params) => {
        this.loading = true;
        this.flag = false;
        goalDetail.editGoalField(params).then(action(res=>{
            if(res.status){
                if(params.tagtype=="2" || params.tagtype=="3"){
                    this.getSubGoalList({ goalId: this.detailKey,type:'father'});
                }

                let list = toJS(this.goalLog.list)
                if(res.logMap){
                    if(res.logMap instanceof Array && res.logMap.length > 0){
                         list = res.logMap.concat(list);
                    }else{
                     list.unshift(res.logMap)
                    }
                }
                this.goalLog.list = list;
                this.setButton(this.isSpecial,this.detailData.status,this.detailData.canedit,this.detailData.canDelete)
                // if(typeof params.setBtn === "function"){
                //     params.setBtn(this.isSpecial,this.detailData.status,this.detailData.canedit);
                // }
                if (typeof params.doback === "function") {
                    if(params.fieldname == 'deleted'){
                         params.doback(params.goalId);
                         message.success(getLabel(20461,'删除成功'));
                         return;
                    }else if(params.fieldname == 'tag'){
                        params.doback(res.status,res.msg,res.goalTagMap);
                    }else if(params.fieldname == "principalid"){
                        params.doback(res.code,res.errormsg)
                    }else{
                        params.doback();
                    }   
                }
                if(!params.isNotMessage && res.code == 0){  
                    message.success(getLabel(31439,'更新成功'))
                }
            }else if(!res.api_status){
                message.error(res.msg || getLabel('25009','失败'));
            }
            this.loading = false;
            this.flag = true;
        }));
    }

    //获取日志
    @action
    getGoalLog = (params) => {
        this.loading = true;
        goalDetail.getGoalLog(params).then(action(res=>{
            if(res.status){
                if(params.type && params.type == "more"){
                    this.goalLog.list =  this.goalLog.list.concat(res.list); 
                }else{
                     this.goalLog.list =  res.list; 
                }
                this.goalLog.lastid = res.lastlogid;
                this.goalLog.lastcount = res.lastlogcount; 
                this.loading = false;
                
            }else if(!res.api_status){
                this.loading = false;
                message.error(res.msg || getLabel('25009','失败'));
            }else{
                this.loading = false;
            }
        }));
    }

    //是否关注
    @action
    updateGoalSpecial = (params) => {
        this.loading = true;
        goalDetail.updateGoalSpecial(params).then(action(res=>{
            if(res.status){
                this.isSpecial = !this.isSpecial; 
                let list = toJS(this.goalLog.list)
                list.unshift(res.logMap)
                this.goalLog.list = list;

                if (typeof params.doback === "function") {
                     params.doback();
                }
                message.success(getLabel(31439,'更新成功'))
            }else if(!res.api_status){
                message.error(res.msg || getLabel(25009,'失败'));
            }
            this.loading = false;
        }));
    }

    @action
    editStatus = (params) => {
        this.loading = true;
        goalDetail.editStatus(params).then(action(res=>{
            if(res.status){
                let list = toJS(this.goalLog.list)
                list.unshift(res.logMap)
                this.goalLog.list = list;
                this.detailData.status = params.status;
                if(res.datas){ //已完成反馈值
                    this.feedBackData.list.unshift(res.datas[0])
                }

                if(params.status == "2"){
                    this.detailData.canedit = res.canedit;
                    this.detailData.caneditPrincial = res.caneditPrincial;
                }
                if (typeof params.doback === "function") {
                    if(params.status == '4'){
                         params.doback(params.goalId);
                         message.success(getLabel(20461,'删除成功'));
                         return;
                    }else{
                        params.doback();
                    }   
                }

                message.success(getLabel(31439,'更新成功'))
            }else if(!res.api_status){
                message.error(res.msg || getLabel('25009','失败'));
            }
            this.loading = false;
        }));
    }

    @action
    addGoal = (params) =>{
        this.loading = true;
        goalDetail.addGoal(params).then(action(res=>{
            if(res.status){
                if(res.code == 0){
                    message.success(getLabel('30700', '操作成功'));
                    if (typeof params.doback === "function") {
                        let opt = {}
                        opt.datas = res.datas;
                        opt.subdatas = res.subdatas;
                        opt.optkey = res.goalId;
                        opt.opttype = 'dialogAdd'
                        params.doback(opt);
                    }
                }else {
                    message.error(res.msg || getLabel('25009','失败'));
                }
            }else{
                message.error(res.msg || getLabel('25009','失败'));
            }
            this.loading = false;
        }));
    }


    @action("设置分享查询")
    getShareSearch = (params) => {
        this.loading = true;
        // let params = {
        //     operate:'search',
        //     workrelatetype:'1',
        //     hasRight:this.detailData.cancreate,
        //     bizid:this.detailKey,
        //     // resourceid:this.resourceid
        // }
        params.operate = 'search';
        params.hasRight = this.detailData.cancreate;
        params.bizid = this.detailKey;
        goalCommonAPI.workrelateShare(params).then(action(res => {
            this.loading = false;
            if (res.status) {
                this.shareConditioninfo = res.conditioninfo;
                this.shareTableStore.getDatas(res.datas)
            } else {
                message.error(res.msg || getLabel('508818', '接口调用失败！'))
            }
        }));
    }

    @action("共享新增删除")
    shareOperate = (params) => {
        this.loading = true;
        goalCommonAPI.workrelateShare(params).then(action(res => {
            if (res.status) {
                if (!res.hasRight) {
                    message.error(getLabel('2012', '对不起，您暂时没有权限！'));
                } else {
                    message.success(getLabel('30700', '操作成功'));
                }
                if(typeof params.doback === "function"){
                    params.doback();
                }
            } else {
                message.error(res.msg || getLabel('508818', '接口调用失败！'))
            }
            this.loading = false;
        }));
    }

    @action
    setOptionsType = (cateList) => {
        this.optionTypes = [];
        if(Util.isEmpty(cateList)){
            return;
        }
        for (let i = 0; i < cateList.length; i++) {
            let option = {};
            option.key = cateList[i].id;
            option.showname = cateList[i].catename;
            this.optionTypes.push(option);
        }
    }

    @action
    viewDocFiled = params =>{
        goalDetail.viewDocFiled(params).then(action((data) => {
          if(data.status){
             params.doback();
          }
     }));
    }

    //设置数据顶部数据
    @action
    setButton = (isSpecial,status,canedit,canDelete) => {
        let btns = [];
        if(isSpecial){
            btns.push(
                {
                    id:'0',
                    key:'isSpecial',
                    value:[getLabel(25436,'关注'),getLabel(384419,'已关注')],
                    type:['ghost','primary'],     
                    valid:1,
                    tip:[getLabel(26939,'添加关注') ,getLabel(26938,'取消关注')]
                }
            )
        }else{
                btns.push(
                {
                    id:'0',
                    key:'isSpecial',
                    value:[getLabel(25436,'关注'),getLabel(384419,'已关注')],
                    type:['ghost','primary'],     
                    valid:0,
                    tip:[getLabel(26939,'添加关注') ,getLabel(26938,'取消关注')]
                }
            )
        }
        if(canedit){
            if(status == '1'){
                btns.push(
                    {
                        id:'1',
                        key:'complete',
                        value:[getLabel(555,'完成'),getLabel(23774,'已完成')],
                        type:['ghost','primary'],     
                        valid:0,
                        tip:[getLabel(382574,'设置为完成'),getLabel(382573,'设置为进行中')]
                    },
                    {
                        id:'2',
                        key:'revoker',
                        value:[getLabel(23757,'撤销'),getLabel(1981,'已撤销')],
                        type:['ghost','primary'],   
                        valid:0,     
                        tip:[getLabel(382575,'设置为撤销'),getLabel(382573,'设置为进行中')]
                    }
                )
            }else if(status == '2'){
                btns.push(
                    {
                        id:'1',
                        key:'complete',
                        value:[getLabel(555,'完成'),getLabel(23774,'已完成')],
                        type:['ghost','primary'],     
                        valid:1,
                        tip:[getLabel(382574,'设置为完成'),getLabel(382573,'设置为进行中')]
                    }
                )
            }else{
                btns.push(
                    {
                        id:'2',
                        key:'revoker',
                        value:[getLabel(23757,'撤销'),getLabel(1981,'已撤销')],
                        type:['ghost','primary'],   
                        valid:1,    
                        tip:[getLabel(382575,'设置为撤销'),getLabel(382573,'设置为进行中')]
                    }
                )
            }
        }
        btns.push(
            {
                id:'0',
                key:'feedback',
                value:[getLabel(21950,'反馈')],
                type:['ghost'],     
                valid:0,
                tip:[getLabel(509102,'添加反馈')]
            } 
        )
        if(canDelete){
            btns.push(
                {
                    id:'3',
                    key:'delete',
                    value:[getLabel(91,'删除')],
                    type:['ghost'],   
                    valid:0,  
                    tip:[getLabel(508590,'删除目标')]
                }
            );
        }    
        this.topBtns = btns;
    }

    @action
    setOptparams = (data) =>{
        this.localtime = new Date().getTime();
        this.optparams = data;
        this.optparams.datas = data.subdatas;
    }

    @action
    setParentData = (data) =>{
        this.parentData = data;
    }

    @action
    setDetailKey = (data) =>{
        this.detailKey = data;
    }

    @action
    setCategory = (data) =>{
        this.category = data;
    }

    @action
    setMaxUploadSize = (data) =>{
        this.maxUploadSize = data;
    }

    @action
    setIconType = (data) =>{
        this.iconType = data;
    }

    @action
    setDisabled = (v) =>{
        this.disabled = v;
    }

    @action
    changeTagChoiceBoxVisible = (visible) => {
        this.tagChoiceBoxVisible = visible
    }

    @action
    changeTaskitemTaglistPopoverVisible = (visible) => {
        this.taskitemTaglistPopoverVisible = visible
    }
    
    @action
    changGoalLogList = (data) =>{
        let list = toJS(this.goalLog.list)
        list.unshift(data);
        this.goalLog.list = list;
    }

    @action
    changeSubTagBoxVisible = (visible,_type,key) => {
        this.subtagvisible = visible;
        this.opentagtype = _type;
        this.selectgoalid = key;
    }

    @action("批量删除")
    batchDelGoal = params =>{
        this.loading = true;
        params.operation = "batchDel";
        goalCommonAPI.editStatus(params).then(action((data) => {
            this.getSubGoalList( { goalId: this.detailKey, type: "father" });
            if(params.doback){
                params.doback(data.status);
            }
            this.loading = false;
        }))
    }

    @action("重置dropdisplay,allCheckBoxVal")
    setDropDisplay(isSelect,isallselect){
       if(isSelect){
          this.dropdisplay = false;
          if(isallselect){
             this.allCheckBoxVal = "1";
          }else{
             this.allCheckBoxVal = "0";
          }
       }else{
          this.dropdisplay = true;
          this.allCheckBoxVal = "0";
       }
    }
}